<?php

function http_parse_params_array( $params )
{
	$result = http_parse_params( $params, HTTP_PARAMS_ALLOW_COMMA | HTTP_PARAMS_ALLOW_FAILURE );
	return $result->params;
}



if( !defined('HTTP_PARAMS_ALLOW_COMMA') )
{
	define('HTTP_PARAMS_ALLOW_COMMA',1);
	define('HTTP_PARAMS_ALLOW_FAILURE',2);
	define('HTTP_PARAMS_RAISE_ERROR',4);
	define('HTTP_PARAMS_DEFAULT',7);
}

if ( !is_callable('http_parse_params' ) ) :

function http_parse_params_split( $string, $delim, $quote = '"' )
{
	$r = array( );
	$i = 0;

	$prevpart = '';
	$token = $delim;
	$part = strtok($string, $token);
	do {
		if( strpos($part, $quote) !== false && strrpos($part, $quote) === strpos($part, $quote) ) {
			//var_dump( '"p'.$i. '|'.strrpos($part, $quote) . '|'. strpos($part, $quote) );
			//var_dump( '".'.$i. '|'.$prevpart.'|'.$part );
			$prevpart = $part.$token;
			$part = strtok($quote) . $quote;
			$r[] = $prevpart . $part;
			
			$prevpart = '';
			$part = strtok($token);
			if( !$part ) break;
			//var_dump( '"!'.$i. '|'.$prevpart.'|'.$part );
		}
		
		$r[] = $prevpart . $part;
		$prevpart = '';
		//var_dump( $token.'|'.$i. '|'.$prevpart.'|'.$part );
		$i++;
	} while($part = strtok($token));
	
	return $r;
}

function http_parse_params_dequote( $string, $quote = '"' )
{
	if( mb_substr($string,0,1) == $quote && mb_substr($string,-1,1) == $quote && mb_substr($string,-2,1) != '\\' )
	{
		$string = mb_substr($string,1,-1);
	}

	return $string;
}

function http_parse_params( $params )
{
	$result = array( );
	$preresult = array( );

	$params = str_replace( "\\\"", "\0\0", $params );
	
	foreach( http_parse_params_split( $params, ';' ) as $p0 )
	foreach( http_parse_params_split( $p0, ',' ) as $p1 )
	foreach( http_parse_params_split( $p1, ' ' ) as $param )
	{
		//$subparams = http_parse_params_split( $param, ',' );
		$pos = mb_strpos($param,'=');
		//var_dump( $param );*/
		if( $pos === false )
			$result[] = str_replace( "\0\0", "\"", http_parse_params_dequote( trim($param) ) );
		else
			$result[][trim(mb_substr($param,0,$pos))] = str_replace( "\0\0", "\"", http_parse_params_dequote( trim(mb_substr($param,$pos+1)) ) );
		//$result[] = isset($result_param[0])&&count($result_param)==1 ? reset($result_param) : $result_param;
	}

	$result_object = new stdClass( );
	$result_object->params = $result;

	return $result_object;
}
endif;